package org.example.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.example.common.R;
import org.example.entity.*;
import org.example.service.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * TODO 类描述
 *
 * @author shaoxuan.
 * @date 2023/12/23 21:50
 */
@Slf4j
@RestController
@RequestMapping("/order")
@Api(tags = "订单管理")

public class OrderController {

    @Autowired
    private OrdersService service;
    @Autowired
    private UserService userService;
    @Autowired
    private AddressBookService addressBookService;
    @Autowired
    private BusinessService businessService;
    @Autowired
    private EmployeeService employeeService;
    @Autowired
    private CabinetsService cabinetsService;
    @Autowired
    private CartService cartService;
    @Autowired
    private DishService dishService;

    /**
     * 用户提交订单
     *
     * @param orders
     * @return
     */
    @PostMapping("/add")
    @ApiOperation(value = "用户提交订单")

    public R<Orders> addOrder(@RequestBody Orders orders) {
        service.save(orders);
        //用户扣钱
        BigDecimal amount = orders.getAmount();
        User user = userService.getById(orders.getUserId());
        Double balance = user.getBalance();
        user.setBalance(balance -= amount.doubleValue());
        userService.updateById(user);
        return R.success(orders);
    }


    /**
     * 根据用户ID查询用户订单
     *
     * @param id
     * @return
     */
    @GetMapping("/userGet/{id}")
    @ApiOperation(value = "根据用户ID查询用户订单")

    public R<List<OrderDto>> getUserOrders(@PathVariable("id") String id) {
        List<Orders> list = service.list(new LambdaQueryWrapper<Orders>().eq(Orders::getUserId, id));
        List<OrderDto> res = new ArrayList<>();
        list.forEach(item -> {
            OrderDto orderDto = new OrderDto();
            BeanUtils.copyProperties(item, orderDto);
            //获取地址
            AddressBook one = addressBookService.getOne(new LambdaQueryWrapper<AddressBook>().
                    eq(AddressBook::getId, item.getAddressBookId()));
            if (one != null) {
                orderDto.setAddressBookName(one.getProvinceName() + one.getCityName() + one.getDetail());
            }
            //获取外卖员名字
            LambdaQueryWrapper<Employee> employeeWrapper = new LambdaQueryWrapper<Employee>()
                    .eq(Employee::getId, item.getEmployeeId());
            Employee employee = employeeService.getOne(employeeWrapper);
            if (employee != null) {
                orderDto.setEmployeeName(employee.getName());
            }
            //获取店家名字
            Business bus = businessService.getOne(new LambdaQueryWrapper<Business>()
                    .eq(Business::getId, item.getBusinessId()));
            if (bus != null) {
                orderDto.setBusinessName(bus.getName());
            }
            //获取外卖柜位置
            Cabinets cabinets = cabinetsService.getOne(new LambdaQueryWrapper<Cabinets>()
                    .eq(Cabinets::getId, item.getCabinetid()));
            if (cabinets != null) {
                orderDto.setCabinetAddress(cabinets.getAddress());
            }
//            //购物车查询
//            List<Cart> cartList = cartService.list(new LambdaQueryWrapper<Cart>().eq(Cart::getUserid, id));
//            List<Dish> DishList = new ArrayList<>();
//            cartList.forEach(cartItem -> {
//                Dish dish = dishService.getById(cartItem.getDishid());
//                DishList.add(dish);
//            });
//            if(DishList!=null){
//                orderDto.setDishList(DishList);
//            }
            res.add(orderDto);
        });
      /*  for (int i = 0; i < list.size(); i++) {
            Orders orders = list.get(i);
            OrderDto orderDto = new OrderDto();
            BeanUtils.copyProperties(orders, orderDto);
            //获取地址
            AddressBook one = addressBookService.getOne(new LambdaQueryWrapper<AddressBook>().
                    eq(AddressBook::getId, orders.getAddressBookId()));
            if(one!=null){
                orderDto.setAddressBookName(one.getProvinceName() + one.getCityName() + one.getDetail());
            }
            //获取外卖员名字
            LambdaQueryWrapper<Employee> employeeWrapper = new LambdaQueryWrapper<Employee>()
                    .eq(Employee::getId, orders.getEmployeeId());
            Employee employee = employeeService.getOne(employeeWrapper);
            if(employee!=null){
                orderDto.setEmployeeName(employee.getName());
            }
            //获取店家名字
            Business bus = businessService.getOne(new LambdaQueryWrapper<Business>()
                    .eq(Business::getId, orders.getBusinessId()));
            if(bus!=null){
                orderDto.setBusinessName(bus.getName());
            }
            //获取外卖柜位置
            Cabinets cabinets = cabinetsService.getOne(new LambdaQueryWrapper<Cabinets>()
                    .eq(Cabinets::getId, orders.getCabinetid()));
            if(cabinets!=null){
                orderDto.setCabinetAddress(cabinets.getAddress());
            }
            List<Cart> cartList = cartService.list(new LambdaQueryWrapper<Cart>().eq(Cart::getUserid, id));
            cartList.forEach(item->{

            });
            res.add(orderDto);
        }*/
        return R.success(res);
    }


    /**
     * 根据店家ID查询所有订单
     *
     * @param id
     * @return
     */
    @GetMapping("/businessGet/{id}")
    @ApiOperation(value = "根据店家ID查询所有订单")
    public R<List<OrderDto>> getBusinessOrders(@PathVariable("id") String id) {
        List<Orders> list = service.list(new LambdaQueryWrapper<Orders>().eq(Orders::getBusinessId, id));
        List<OrderDto> res = new ArrayList<>();
        list.forEach(item->{
            OrderDto orderDto = new OrderDto();
            BeanUtils.copyProperties(item, orderDto);
            //获取地址
            AddressBook one = addressBookService.getOne(new LambdaQueryWrapper<AddressBook>().
                    eq(AddressBook::getId, item.getAddressBookId()));
            if (one != null) {
                orderDto.setAddressBookName(one.getProvinceName() + one.getCityName() + one.getDetail());
            }
            //获取外卖员名字
            LambdaQueryWrapper<Employee> employeeWrapper = new LambdaQueryWrapper<Employee>()
                    .eq(Employee::getId, item.getEmployeeId());
            Employee employee = employeeService.getOne(employeeWrapper);
            if (employee != null) {
                orderDto.setEmployeeName(employee.getName());
            }
            //获取店家名字
            Business bus = businessService.getOne(new LambdaQueryWrapper<Business>()
                    .eq(Business::getId, item.getBusinessId()));
            if (bus != null) {
                orderDto.setBusinessName(bus.getName());
            }
            //获取外卖柜位置
            Cabinets cabinets = cabinetsService.getOne(new LambdaQueryWrapper<Cabinets>()
                    .eq(Cabinets::getId, item.getCabinetid()));
            if (cabinets != null) {
                orderDto.setCabinetAddress(cabinets.getAddress());
            }
            res.add(orderDto);

        });
        return R.success(res);
    }

    /**
     * 根据订单ID查询订单
     *
     * @param id
     * @return
     */
    @GetMapping("/getByEmployeeId/{id}")
    @ApiOperation(value = "根据外卖员ID查询订单")

    public R<List<OrderDto>> getById(@PathVariable("id") String id) {
        List<Orders> list = service.list(new LambdaQueryWrapper<Orders>().eq(Orders::getEmployeeId, id));


        List<OrderDto> res = new ArrayList<>();
        list.forEach(item->{
            OrderDto orderDto = new OrderDto();
            BeanUtils.copyProperties(item, orderDto);
            //获取地址
            AddressBook one = addressBookService.getOne(new LambdaQueryWrapper<AddressBook>().
                    eq(AddressBook::getId, item.getAddressBookId()));
            if (one != null) {
                orderDto.setAddressBookName(one.getProvinceName() + one.getCityName() + one.getDetail());
            }
            //获取外卖员名字
            LambdaQueryWrapper<Employee> employeeWrapper = new LambdaQueryWrapper<Employee>()
                    .eq(Employee::getId, item.getEmployeeId());
            Employee employee = employeeService.getOne(employeeWrapper);
            if (employee != null) {
                orderDto.setEmployeeName(employee.getName());
            }
            //获取店家名字
            Business bus = businessService.getOne(new LambdaQueryWrapper<Business>()
                    .eq(Business::getId, item.getBusinessId()));
            if (bus != null) {
                orderDto.setBusinessName(bus.getName());
            }
            //获取外卖柜位置
            Cabinets cabinets = cabinetsService.getOne(new LambdaQueryWrapper<Cabinets>()
                    .eq(Cabinets::getId, item.getCabinetid()));
            if (cabinets != null) {
                orderDto.setCabinetAddress(cabinets.getAddress());
            }
            res.add(orderDto);

        });
        return R.success(res);
    }

    @GetMapping("/getUnExcpet")
    @ApiOperation(value = "查询未接单的订单")

    public R<List<OrderDto>> getUnExcpet() {
        List<Orders> list = service.list(new LambdaQueryWrapper<Orders>().eq(Orders::getStatus, 2));


        List<OrderDto> res = new ArrayList<>();
        list.forEach(item->{
            OrderDto orderDto = new OrderDto();
            BeanUtils.copyProperties(item, orderDto);
            //获取地址
            AddressBook one = addressBookService.getOne(new LambdaQueryWrapper<AddressBook>().
                    eq(AddressBook::getId, item.getAddressBookId()));
            if (one != null) {
                orderDto.setAddressBookName(one.getProvinceName() + one.getCityName() + one.getDetail());
            }
            //获取外卖员名字
            LambdaQueryWrapper<Employee> employeeWrapper = new LambdaQueryWrapper<Employee>()
                    .eq(Employee::getId, item.getEmployeeId());
            Employee employee = employeeService.getOne(employeeWrapper);
            if (employee != null) {
                orderDto.setEmployeeName(employee.getName());
            }
            //获取店家名字
            Business bus = businessService.getOne(new LambdaQueryWrapper<Business>()
                    .eq(Business::getId, item.getBusinessId()));
            if (bus != null) {
                orderDto.setBusinessName(bus.getName());
            }
            //获取外卖柜位置
            Cabinets cabinets = cabinetsService.getOne(new LambdaQueryWrapper<Cabinets>()
                    .eq(Cabinets::getId, item.getCabinetid()));
            if (cabinets != null) {
                orderDto.setCabinetAddress(cabinets.getAddress());
            }
            res.add(orderDto);

        });
        return R.success(res);
    }

    /**
     * 修改订单状态  订单状态 1待付款，2待派送，3已派送，4已完成，5已取消
     *
     * @param orders
     * @return
     */
    @PutMapping("/updateStauts")
    @ApiOperation(value = "修改订单状态  订单状态 1待付款，2待派送，3已接单，4已派送，5已完成，6已取消")

    public R<String> update(@RequestBody Orders orders) {
        if (service.updateById(orders)) {
            return R.success("修改成功！");
        } else {
            return R.success("修改失败！");
        }
    }

}
